/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jmediaplayer;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import jtmdb.GeneralSettings;
import jtmdb.Movie;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import org.json.JSONException;

/**
 *
 * @author Deano
 */

public class UsefulFunctions {

	private static List<Movie> movies = null;

	/**
	* Does a movie search by name and returns the results.
	* @param FilmName  the name of the film you are looking for.
	* @return          A new List<Movie> with the movie information.
	*/
	public static List searchJTMDB(String FilmName) {
		try {
			//Search for the movie?
			GeneralSettings.setApiKey("7670a7353150caf06e3f6d8219f0469e");
			movies = Movie.search(FilmName);
		} catch (IOException ex) {
			Logger.getLogger(UsefulFunctions.class.getName()).log(Level.SEVERE, null, ex);
		} catch (JSONException ex) {
			Logger.getLogger(UsefulFunctions.class.getName()).log(Level.SEVERE, null, ex);
		}

		return movies;
	}

	/**
	* Reallocates an array with a new size, and copies the contents
	* of the old array to the new array.
	* @param oldArray  the old array, to be reallocated.
	* @param newSize   the new array size.
	* @return          A new array with the same contents.
	*/
	public static Object resizeArray(Object oldArray, int newSize) {
	   int oldSize = java.lang.reflect.Array.getLength(oldArray);
	   Class elementType = oldArray.getClass().getComponentType();
	   Object newArray = java.lang.reflect.Array.newInstance(elementType,newSize);
	   int preserveLength = Math.min(oldSize,newSize);

	   if (preserveLength > 0) {
		  System.arraycopy(oldArray,0,newArray,0,preserveLength);
	   }

	   oldArray = null;
	   oldSize = 0;
	   elementType = null;
	   preserveLength = 0;

	   return newArray;
	}

	/**
	* Causes java to wait a little while.
	* @param milliseconds	Time to wait in milliseconds.
	* @return				When the timer ends.
	*/
	public static void waiting (int msec){
        long t0, t1;

        t0 =  System.currentTimeMillis();
        do {
			t1 = System.currentTimeMillis();
        }
        while (t1 - t0 < msec);

		t0 = 0;
		t1 = 0;
    }

	/**
	* Download a file from a URL.
	* @param imageUrl	The URL of the file you wish to download.
	* @param destFile	Where you would like the file to be downloaded to without the extension.
	* @return			If the operation was complete or not.
	*/
	public static String downloadImage(String fileUrl, String destFile) {
		return downloadImage(fileUrl, destFile, null);
	}

	/**
	* Download a file from a URL.
	* @param fileUrl	The URL of the file you wish to download.
	* @param destFile	Where you would like the file to be downloaded to without the extension.
	* @param ext		The extension you wish the file to be saved as without the period (.), if you leave this blank the extension is taken from the url.
	* @return			The file path of the new image, or null if there was a problem.
	*/
	public static String downloadImage(String fileUrl, String destFile, String ext) {

		try {

			URL url = new URL(fileUrl);

			//Work out the extension
			if (ext == null) {
				String surl = fileUrl;
				//remove any ?
				int qmark = surl.lastIndexOf("?");
				if (qmark > 0) {
					surl = surl.substring(0,qmark);
				}

				//Get extension
				int dot = surl.lastIndexOf(".");
				if (dot > 0) {
					ext = surl.substring(dot+1,surl.length());
				} else {
					return null;
				}

				System.out.println(ext);
			}

			InputStream is = url.openStream();
			OutputStream os = new FileOutputStream(destFile + "." + ext);

			byte[] b = new byte[2048];
			int length;

			while ((length = is.read(b)) != -1) {
				os.write(b, 0, length);
			}

			is.close();
			os.close();
			b = null;
			length = 0;

			return destFile + "." + ext;
		} catch (IOException ex) {
			Logger.getLogger(UsefulFunctions.class.getName()).log(Level.SEVERE, null, ex);
			return null;
		}

	}

	/**
	* Resize an image
	* @param sourceImg	The source of the image to resize.
	* @param destImg	The destination of the resized image.
	* @param Width		The maximum width you want the new image to be, use 0 for source width.
	* @param Height		The maximum height you want the new image to be, use 0 for source height.
	* @return			true if successful and false if unsuccessful.
	*/
	public static Boolean resizeImage(String sourceImg, String destImg, Integer Width, Integer Height) {
		BufferedImage origImage;
		try {

			origImage = ImageIO.read(new File(sourceImg));
			int type = origImage.getType() == 0? BufferedImage.TYPE_INT_ARGB : origImage.getType();

			//*Special* if the width or height is 0 use image src dimensions
			if (Width == 0) {
				Width = origImage.getWidth();
			}
			if (Height == 0) {
				Height = origImage.getHeight();
			}

			int fHeight = Height;
			int fWidth = Width;

			//Work out the resized width/height
			if (origImage.getHeight() > Height || origImage.getWidth() > Width) {
				fHeight = Height;
				int wid = Width;
				float sum = (float)origImage.getWidth() / (float)origImage.getHeight();
				fWidth = Math.round(fHeight * sum);

				if (fWidth > wid) {
					//rezise again for the width this time
					fHeight = Math.round(wid/sum);
					fWidth = wid;
				}
			}

			BufferedImage resizedImage = new BufferedImage(fWidth, fHeight, type);
			Graphics2D g = resizedImage.createGraphics();
			g.setComposite(AlphaComposite.Src);

			g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
			g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
			g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

			g.drawImage(origImage, 0, 0, fWidth, fHeight, null);
			g.dispose();

			ImageIO.write(resizedImage, "png", new File(destImg));

		} catch (IOException ex) {
			Logger.getLogger(UsefulFunctions.class.getName()).log(Level.SEVERE, null, ex);
			return false;
		}

		return true;
	}
}
